package com.atguigu.dga.meta.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.meta.bean.TableMetaInfo;
import com.atguigu.dga.meta.bean.TableMetaInfoExtra;
import com.atguigu.dga.meta.bean.TableMetaInfoQuery;
import com.atguigu.dga.meta.bean.TableMetaInfoVO;
import com.atguigu.dga.meta.service.TableMetaInfoExtraService;
import com.atguigu.dga.meta.service.TableMetaInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.hadoop.io.retry.AtMostOnce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author liuxu
 * @since 2023-10-09
 */
@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {

    @Autowired
    private TableMetaInfoService tableMetaInfoService;

    @Autowired
    private TableMetaInfoExtraService tableMetaInfoExtraService;

    //http://dga.gmall.com/tableMetaInfo/table-list?schemaName=gmall&tableName=&dwLevel=&pageSize=20&pageNo=1
    @GetMapping("/table-list")
    public String initTables(TableMetaInfoQuery tableMetaInfoQuery){

        //获取list数据
        List<TableMetaInfoVO> gettablelist = tableMetaInfoService.gettablelist(tableMetaInfoQuery);

        Integer count = tableMetaInfoService.gettablecount(tableMetaInfoQuery);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",count);
        jsonObject.put("list",gettablelist);

        String json=jsonObject.toJSONString();
        System.out.println("json = " + json);
        return json;

    }

    @GetMapping("/table/{tableMetaInfoId}")
    public String table(@PathVariable("tableMetaInfoId") Long id){
        TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(id);
        TableMetaInfoExtra one = tableMetaInfoExtraService.getOne(
                new QueryWrapper<TableMetaInfoExtra>().eq("table_name", tableMetaInfo.getTableName()).
                        eq("schema_name", tableMetaInfo.getSchemaName())
        );
        tableMetaInfo.setTableMetaInfoExtra(one);
        return JSON.toJSONString(tableMetaInfo);
    }

    @PostMapping("/tableExtra")
    public String setTable(@RequestBody TableMetaInfoExtra tableMetaInfoExtra){
        tableMetaInfoExtra.setUpdateTime(new Date());
        tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra);
        return "success";
    }

    @PostMapping("init-tables/{database}/{assessdate}")
    public String inittable(@PathVariable("database")String database ,@PathVariable("assessdate")String assessdate) throws Exception {

        tableMetaInfoService.initTableMetaInfo(database,assessdate);
        return "success";
    }

}
